<template>
	<labels v-bind="$attrs">
		<view class="clear father" style="left: -5px;">
			
			<images class="fl" :list="list" :width="80" :count="count" @remove="remove" :disabled="false"></images>
			
			<view class="w80 fl pd5" @tap="chooseImage" v-if="list.length < count || count == -1">
				<view class="square">
					<view class="flex ct bd rds4 hover">
						<view class="bIcon-photoFill  gray fz24 op6"></view>
					</view>
				</view>
			</view>
			
			<input type="text" :maxlength="-1" :name="name" :value="curValue" class="none">
			
		</view>
	</labels>
</template>

<script>
	export default {
		name:"upload-images",
		model: {
			prop: "value",
			event: "bindModel"
		},
		props:{
			count : {
				default : -1 
			},
			name : {
				default : "" 
			},
			value : {
				default : function(e){
					return [] ;
				}
			},
			deleteUrl:{
				default : ""
			}
		},
		data() {
			return {
				list : [] ,
				mime2ext : {
				  'image/png': 'png',
				  'image/jpeg': 'jpg',
				  'image/gif': 'gif',
				  'image/svg+xml': 'svg',
				  'image/bmp': 'bmp',
				  'image/webp': 'webp'
				},
				totalSize : 0 ,
				files : []
			};
		},
		created() {
			this.list = this.getValueList(this.value);
		},
		computed:{
			curValue:function(e){
				return this.list.join(",") ;
			}
		},
		watch:{
			value : function(e){
				this.list = this.getValueList(this.value);
			}
		},
		methods:{
			
			getValueList:function(value){
				if (value !== 0 && value !== false && !value) {
					return [] ;
				}
				if (Array.isArray(value)) {
					return value ;
				}
				return (value+"").split(",");
			},
			
			chooseImage:function(e){
				uni.chooseImage({
					count: this.count > 1 ? this.count : 1 , 
					success: (res) => {
						var files = res.tempFiles ;
						this.totalSize = files.map(item=>item.size).reduce((total,size) => total + size );
						this.uploadSize = 0 ;
						this.files = files ;
						this.doUpload(0);
					}
				});
			},
			
			doUpload:function(index){
				if (index > this.files.length - 1 || (this.count !=-1 && this.list.length >= this.count)) {
					this.files = [] ;
					uni.hideLoading();
					return ;
				}
				var file = this.files[index];
				uniCloud.uploadFile({
					filePath: file.path ,
					cloudPath: this.getCloudPath(file) ,
					onUploadProgress:e => {
						var percent = (((this.uploadSize + e.loaded)/this.totalSize)*100) ;
						var progress = (percent > 100 ? 100 : percent).toFixed(2) ; 
						uni.showLoading({
							title: progress + "%"
						});
						if (e.loaded ==  e.total) {
							this.uploadSize += e.total ;
						}
					},
					success: (e) => {
						var fileId = e.fileID ;
						this.list.push(fileId);
						this.changed();
						index ++ ;
						this.doUpload(index);
					},
					fail: (err) => {
						console.log("上传失败：",err);
						uni.showModal({
							title:'上传失败',
							content: JSON.stringify(err) ,
							showCancel:false,
							confirmColor:'#07c160'
						});
					}
				})
			},
			
			guid : function () {
			    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
			        var r = Math.random() * 16 | 0,
			            v = c == 'x' ? r : (r & 0x3 | 0x8);
			        return v.toString(16);
			    });
			},
			
			getCloudPath:function(file){
				var fileType = this.getExtension(file.type) ;
				return `${this.guid()}.${fileType}` ;
			},
			
			getExtension:function(contentType) {
			  return this.mime2ext[contentType] ;
			},
			
			remove:function(e){
				var index = e.detail.value ;
				var fileID = this.list[index];
				if (!this.deleteUrl) {
					this.list.splice(index,1);
					this.$emit("delete" , {detail:{value:fileID}});
					this.changed();
					return ;
				}
				this.deleteRemote(fileID);
			},
			
			deleteRemote:function(fileID , index){
				this.bcc.call({
					url : this.deleteUrl ,
					data : {fileID},
					success : res => { 
						this.list.splice(index,1);
						this.$emit("delete" , {detail:{value:fileID}});
						this.changed();
					}
				});
			},
			
			changed:function(e){
				this.$emit("change" , {deital : {value : this.list }});
				this.$emit("bindModel" , this.list.join(",") );
			},
			
			preview:function(url){
				uni.previewImage({
					urls:this.list ,
					current: url
				});
			},
		}
	}
</script>

<style>

</style>
